package com.lv.suyiyong.hfr.ui

import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lv.common.base.BaseActivity
import com.lv.common.dialog.SwipeCatpchaDialog
import com.lv.common.imp.OnDialogSureListener
import com.lv.common.ktx.LoadSrc
import com.lv.common.ktx.initSingleClickListener
import com.lv.common.network.model.DataResult
import com.lv.common.utils.*
import com.lv.common.utils.YgxNetUtilsKt.Companion.sendCode
import com.lv.service.bean.UserInfoOld
import com.lv.service.model.EditorViewModel
import com.lv.service.model.ServiceViewModel
import com.lv.service.net.SendCodeBody
import com.lv.service.net.VerifyCodeBody
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onSuccess

import com.lv.service.repo.UserInfo
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.bean.TokenBean
import com.lv.suyiyong.hfr.databinding.ActivityForgetSecoundBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2023/3/2 7:26 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：忘记密码第二步
 */
@Route(path = ARoutUtils.ForgetPasswordSecoundActivity)
class ForgetPasswordSecoundActivity : BaseActivity<ActivityForgetSecoundBinding>(),
    View.OnClickListener {

    private var timer: TimerUnit? = null
    private var mPhone: String? = null
    private val serviceViewModel: ServiceViewModel by viewModel()
    private val mEditorViewModel by viewModels<EditorViewModel>()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    override fun getLayoutRes() = R.layout.activity_forget_secound
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            vm = mEditorViewModel
            StatusBarUtil.setHeightAndPadding(this@ForgetPasswordSecoundActivity, titleBar)
            titleBar.onClickBackIcon { finish() }
            titleBar.setTitle("忘记密码")
            initSingleClickListener(btnLogin, tvCode)

        }
    }

    private fun showSwipecaptDialog(phone: String) {
        val swipeCatpchaDialog =
            SwipeCatpchaDialog(this, true, true, object : OnDialogSureListener {
                override fun onSureClick(content: String?) {
                    val sendCode = sendCode(phone)
                    sendCode(SendCodeBody(phone, sendCode))
                }
            })
        swipeCatpchaDialog.show()
    }

    private fun sendCode(body: SendCodeBody) {
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async {
                    serviceViewModel.sendCode(body)
                }.await()
            parseSendCodeResult(result)
        }

    }

    private fun parseSendCodeResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<Any> { code, data, message, result ->
                if (timer == null) {
                    timer = TimerUnit(mBinding.tvCode)
                }
                timer?.startTime()
                message?.let { message ->
                    showToast(this@ForgetPasswordSecoundActivity, message)
                }

            }
            onBizError<TokenBean> { code, message, data ->

            }
        }
    }

    override fun initConfig() {
        super.initConfig()
        val userInfo = intent.getParcelableExtra<UserInfo>("userInfo")
        mPhone = userInfo?.phone
        mBinding.ivLogo.LoadSrc(userInfo?.logo)
        mBinding.tvName.text = userInfo?.name

    }


    override fun initData() {
        super.initData()
        LiveEventBus
            .get(LiveEventUtils.FINISH_SETPASSWORDACTIVITY_KEY, String::class.java)
            .observe(this) {
                finish()
            }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_login -> {
                verifyCode(VerifyCodeBody(mPhone!!, mEditorViewModel.obMobile.get()!!))
            }

            R.id.tv_code -> {
                showSwipecaptDialog(mPhone!!)
            }
        }
    }

    private fun verifyCode(body: VerifyCodeBody) {
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async {
                    serviceViewModel.verifyCode(body)
                }.await()
            parseResult(result)
        }
    }

    private fun parseResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<UserInfoOld> { code, data, message, result ->
                ARouter.getInstance().build(ARoutUtils.SetPasswordActivity)
                    .withParcelable("userInfo", data)
                    .navigation()

            }
            onBizError<Any> { code, message, data ->
                showToast(message)
            }
        }
    }

}